/**
 * Friday
 *
 * eg:
 * - 指定日期: friday/friday?date=2020-12-31
 * - 透明背景: friday?position=top-left
 * - 指定颜色: friday?bg=000000&color=ffffff
 *
 * parameter:
 * - date: 指定日期, 可选, 默认当天 (eg: 2020-12-31)
 * - bg: 背景颜色, 可选, 默认 '#000'
 * - color: 字体颜色, 可选, 默认 '#fff'
 * - position: 组件位置, 可选, (eg: top-left), 设置此值时, 即使用`透明背景`
 */

class Friday {

    // 获取油价api
    oilUrl = `http://123.56.117.88:8032/searchOilToday`

    weatherUrl = `http://123.56.117.88:8032/searchWeather`

    gsqWorkScheduleUrl = `http://123.56.117.88:8032/getQQWorkSchedule`

    // get 请求
    async get(url, load = this.loadString) {
        let req = new Request(url)
        req.headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/85.0.4183.102'
        }

        let resp
        if (load == this.loadJSON) {
            resp = await req.loadJSON()
        } else if (load == this.loadImage) {
            resp = await req.loadImage()
        } else {
            resp = await req.loadString()
        }

        if (req.response['statusCode'] !== 200) {
            throw new Error(`请求错误, 状态码: ${req.response['statusCode']}`)
        }

        return resp
    }

    // 周缩写
    weekAbbrs = [
        'SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT',
    ]
    // 表情文本配置
    weekTexts = {
        'DEFAULT': {
            'text': `to friday`,
            'emoji': '🤮',
        },
        'FRI': {
            'text': `it's friday`,
            'emoji': '🎉🎉🎉',
        },
        'SAT': {
            'text': `happy weekend`,
            'emoji': '🥳🥳🥳',
        },
        'SUN': {
            'text': `it's last day`,
            'emoji': '🥺🥺🥺',
        },
    }
    // 字体色
    color = Color.white()
    // 背景色
    bgColor = Color.black()

    constructor(args = {}, loader = null) {
        this.args = args
        this.loader = loader
        this.widgetSize = config.widgetFamily
    }

    // --------------------------------

    // getDateInfo 获取当前日期信息, 也可根据入参进行初始化
    getDateInfo() {
        let date = new Date()
        if (typeof (this.args.date) != 'undefined') {
            date = new Date(this.args.date)
        }
        let dayOfWeek = date.getDay() == 0 ? 7 : date.getDay()
        let weekAbbr = this.weekAbbrs[dayOfWeek]
        let monthDayYang = (date.getMonth() + 1) + '.' + date.getDate()

        //农历
        var yy = date.getFullYear();
        var mm = date.getMonth() + 1;
        var dd = date.getDate();

        var monthDayNong = this.showCal(yy, mm, dd);

        let dateInfo = {
            monthDay: monthDayYang, // 月日
            monthDayNong: monthDayNong, // 月日
            dayOfWeek: dayOfWeek,   // 周几
            weekAbbr: weekAbbr,     // 周几缩写
        }
        if (this.weekTexts[weekAbbr]) {
            dateInfo['textInfo'] = this.weekTexts[weekAbbr]
        } else {
            let weekText = this.weekTexts['DEFAULT']
            let nextFriday = (5 - dayOfWeek + 7) % 7
            let daysText = nextFriday == 1 ? 'day' : 'days'
            dateInfo['textInfo'] = {
                'text': `${nextFriday} ${daysText} ${weekText['text']}`,
                'emoji': weekText['emoji'].repeat(nextFriday),
            }
        }

        return dateInfo
    }

    // --------------------------------

    async render() {
        if (this.widgetSize === 'medium') {
            return await this.renderMedium()
        } else if (this.widgetSize === 'large') {
            return await this.renderLarge()
        } else {
            return await this.renderSmall()
        }
    }

    // renderSmall 渲染小尺寸组件, 默认 multiple 1, 大尺寸时 multiple 为 2
    async renderSmall(multiple = 1) {
        let dateInfo = this.getDateInfo()
        let widget = new ListWidget()
        widget.setPadding(0, 0, 0, 0)

        try {
            if (this.args.color) {
                // 字体颜色
                this.color = new Color(this.args.color, 1)
            }
            if (this.args.position) {
                // 透明背景
                let img = await this.loader.getTransparentBg(
                    this.widgetSize,
                    this.args.position
                )
                widget.backgroundImage = img
            } else {
                // 背景色
                if (this.args.bg) {
                    this.bgColor = new Color(this.args.bg, 1)
                }
                widget.backgroundColor = this.bgColor
            }
        } catch (e) {
            return this.loader.fail(e.message)
        }

        // 周缩写
        let weekArea = widget.addText(dateInfo.weekAbbr)
        weekArea.centerAlignText()
        weekArea.textColor = this.color
        weekArea.font = Font.heavyRoundedSystemFont(40 * multiple)

        widget.addSpacer(5 * multiple)

        // 文本
        let textArea = widget.addText(dateInfo['textInfo']['text'])
        textArea.centerAlignText()
        textArea.textColor = this.color
        textArea.font = Font.heavyRoundedSystemFont(15 * multiple)

        widget.addSpacer(10 * multiple)

        // 表情
        let emojiArea = widget.addText(dateInfo['textInfo']['emoji'])
        emojiArea.centerAlignText()
        emojiArea.font = Font.boldSystemFont(25 * multiple)

        return widget
    }

    async renderMedium(multiple = 1) {
        // return await this.renderSmall()
        let dateInfo = this.getDateInfo()
        let widget = new ListWidget()
        widget.setPadding(0, 30, 0, 20)

        try {
            if (this.args.color) {
                // 字体颜色
                this.color = new Color(this.args.color, 1)
            }
            if (this.args.position) {
                // 透明背景
                let img = await this.loader.getTransparentBg(
                    this.widgetSize,
                    this.args.position
                )
                widget.backgroundImage = img
            } else {
                // 背景色
                if (this.args.bg) {
                    this.bgColor = new Color(this.args.bg, 1)
                }
                widget.backgroundColor = this.bgColor
            }
        } catch (e) {
            return this.loader.fail(e.message)
        }

        // 周缩写
        let todayInfo = widget.addText('Today is ' + dateInfo.monthDay + ' | ' + dateInfo.monthDayNong)
        todayInfo.leftAlignText()
        todayInfo.textColor = this.color
        todayInfo.font = Font.systemFont(12)

        widget.addSpacer(4)
        // 天气
        let weatherJson = await this.get(this.weatherUrl)
        const weather = weatherJson.data.weather
        let weatherImg = '';
        if (weather.weatherimg == 'duoyun.png'){
            weatherImg = '☁️'
        }
        if (weather.weatherimg == 'yin.png'){
            weatherImg = '☁️'
        }
        if (weather.weatherimg == 'qing.png'){
            weatherImg = '☀️'
        }
        if (weather.weatherimg == 'xiaoyu.png'){
            weatherImg = '🌧️'
        }
        if (weather.weatherimg == 'zhongyu.png'){
            weatherImg = '🌧️🌧️'
        }
        if (weather.weatherimg == 'dayu.png'){
            weatherImg = '🌧️🌧️🌧️'
        }
        if (weather.weatherimg == 'baoyu.png'){
            weatherImg = '⛈️️'
        }
        let weatherAre = widget.addText('Weather: ' + '  ' + weatherImg + ' ' + weather.real + ' ; ' + weather.lowest + '~' + weather.highest + '    🌬:' + weather.windsc);
        weatherAre.leftAlignText()
        weatherAre.textColor = this.color
        weatherAre.font = Font.systemFont(12)

        widget.addSpacer(4)


        var weeklist = new Array('☹️', '😭', '🤬', '🥵', '🥳', '🤩', '🤤');
        var lodingline = '{';
        for (var i = 1; i < dateInfo.dayOfWeek ; i++){
            lodingline = lodingline + '■' + '■';
        }

        if (new Date().getHours() >= 12){
            lodingline = lodingline + '■';
        }

        if (new Date().getHours() >= 17){
            lodingline = lodingline + '■■';
        }

        for (var i = lodingline.length; i < 15 ; i = i + 2){
            lodingline = lodingline + '□' + '□';
        }

        lodingline = lodingline + '}';
        let areFriday = widget.addText('Is weekend?' + (dateInfo.dayOfWeek > 5 ? ( '🙆🏽!' + lodingline) : (('🙅🏿 ') + lodingline)));
        areFriday.leftAlignText()
        areFriday.textColor = this.color
        areFriday.font = Font.systemFont(12)

        widget.addSpacer(4)

        // 油价
        let oilJson = await this.get(this.oilUrl)
        const oil = oilJson.data.oil
        let oilAre = widget.addText('Today⛽:' + '    98: ¥' + oil.p98 + '    95: ¥' + oil.p95 + '    92: ¥' + oil.p92);
        oilAre.leftAlignText()
        oilAre.textColor = this.color
        oilAre.font = Font.systemFont(12)

        widget.addSpacer(4)

        // gsq 工作排班
        let workScheduleJson = await this.get(this.gsqWorkScheduleUrl)
        const workSchedule = workScheduleJson.data
        let workScheduleImg = '';
        if (workSchedule.workType == '1'){
            workScheduleImg = '1⃣️'
        }
        if (workSchedule.workType == '2'){
            workScheduleImg = '2⃣️️'
        }
        if (workSchedule.workType == '3'){
            workScheduleImg = '3⃣️'
        }
        if (workSchedule.workType == '4'){
            workScheduleImg = '4⃣️️'
        }
        if (workSchedule.workType == '5'){
            workScheduleImg = '5⃣️️'
        }
        if (workSchedule.workType == '0'){
            workScheduleImg = '0⃣️️'
        }
        if (workSchedule.workType == '生'){
            workScheduleImg = '生'
        }
        if (workSchedule.workType == '值'){
            workScheduleImg = '值'
        }
        if (workSchedule.workType == '中'){
            workScheduleImg = '🀄️'
        }
        let workScheduleAre = widget.addText('💘 work today? ' + ' ' + (workSchedule.isHoliday ? '; No¡' : workScheduleImg) + ' ' +
        '; now ' + (workSchedule.doWhat == 'working' ? '👩‍⚕️' : '💆🏻‍♀️') + '; work off at ' + workSchedule.offWorkTime);
        workScheduleAre.leftAlignText()
        workScheduleAre.textColor = this.color
        workScheduleAre.font = Font.systemFont(12)

        widget.addSpacer(30)


        let date = new Date()
        if (typeof (this.args.date) != 'undefined') {
            date = new Date(this.args.date)
        }
        let hours = date.getHours()
        let minutes = date.getMinutes()

        let refreshAre = widget.addText('🔄 ' + hours + ':' + minutes + '        ');
        refreshAre.centerAlignText()
        refreshAre.textColor = this.color
        refreshAre.font = Font.systemFont(12)
        refreshAre.font.textOpacity = 0.75


        // widget.addSpacer(5 * multiple) ｜███░░░░░░░░░｜

        // 文本
        // let textArea = widget.addText(dateInfo['textInfo']['text'])
        // textArea.centerAlignText()
        // textArea.textColor = this.color
        // textArea.font = Font.heavyRoundedSystemFont(15 * multiple)

        // widget.addSpacer(10 * multiple)

        // 表情
        // let emojiArea = widget.addText(dateInfo['textInfo']['emoji'])
        // emojiArea.centerAlignText()
        // emojiArea.font = Font.boldSystemFont(25 * multiple)

        return widget
    }

    tgString = "甲乙丙丁戊己庚辛壬癸";
    dzString = "子丑寅卯辰巳午未申酉戌亥";
    numString = "一二三四五六七八九十";
    monString = "正二三四五六七八九十冬腊";
    weekString = "日一二三四五六";
    sx = "鼠牛虎兔龙蛇马羊猴鸡狗猪";
    cYear;
    cMonth;
    cDay;
    TheDate = new Date();
//即将过期的历算组
    CalendarData = new Array(0xA4B, 0x5164B, 0x6A5, 0x6D4, 0x415B5, 0x2B6, 0x957, 0x2092F, 0x497, 0x60C96, 0xD4A, 0xEA5, 0x50DA9, 0x5AD, 0x2B6, 0x3126E
        , 0x92E, 0x7192D, 0xC95, 0xD4A, 0x61B4A, 0xB55, 0x56A, 0x4155B, 0x25D, 0x92D, 0x2192B, 0xA95, 0x71695, 0x6CA, 0xB55, 0x50AB5, 0x4DA, 0xA5B, 0x30A57,
        0x52B, 0x8152A, 0xE95, 0x6AA, 0x615AA, 0xAB5, 0x4B6, 0x414AE, 0xA57, 0x526, 0x31D26, 0xD95, 0x70B55, 0x56A, 0x96D, 0x5095D, 0x4AD, 0xA4D, 0x41A4D, 0xD25,
        0x81AA5, 0xB54, 0xB6A, 0x612DA, 0x95B, 0x49B, 0x41497, 0xA4B, 0xA164B, 0x6A5, 0x6D4, 0x615B4, 0xAB6, 0x957, 0x5092F, 0x497, 0x64B, 0x30D4A, 0xEA5, 0x80D65,
        0x5AC, 0xAB6, 0x5126D, 0x92E, 0xC96, 0x41A95, 0xD4A, 0xDA5, 0x20B55, 0x56A, 0x7155B, 0x25D, 0x92D, 0x5192B, 0xA95, 0xB4A, 0x416AA, 0xAD5, 0x90AB5, 0x4BA,
        0xA5B, 0x60A57, 0x52B, 0xA93, 0x40E95, 0x6aa, 0xad5);
    madd = new Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);

    GetBit(m, n) {
        return (m >> n) & 1;
    }

    e2c() {
        var total, m, n, k;
        var isEnd = false;
        var tmp = this.TheDate.getFullYear(); //获取当前年
        if (tmp < 1900) {
            tmp += 1900;
        }
        //天数
        total = (tmp - 1921) * 365 + Math.floor((tmp - 1921) / 4) + this.madd[this.TheDate.getMonth()] + this.TheDate.getDate() - 38;
        //闰年加一天
        if (this.TheDate.getFullYear() % 4 == 0 && this.TheDate.getMonth() > 1) {
            total++;
        }
        //计算月
        //从1921年开始，对照润大小信息表（将16进制转为2进制查看，0表示小月【29天】，1表示大月【30天】）一个月一个月挨个减，直到剩下当前这个月
        for (m = 0;; m++) {
            k = (this.CalendarData[m] < 0xfff) ? 11 : 12;
            for (n = k; n >= 0; n--) {
                if (total <= 29 + this.GetBit(this.CalendarData[m], n)) {
                    isEnd = true;
                    break;
                }
                total = total - 29 - this.GetBit(this.CalendarData[m], n);
            }
            if (isEnd) break;
        }
        this.cYear = 1921 + m;
        this.cMonth = k - n + 1;
        this.cDay = total;
        if (k == 12) {
            if (this.cMonth == Math.floor(this.CalendarData[m] / 0x10000) + 1) {
                this.cMonth = 1 - this.cMonth;
            }
            if (this.cMonth > Math.floor(this.CalendarData[m] / 0x10000) + 1) {
                this.cMonth--;
            }
        }
    }

    GetcDateString() {
        var tmp = "";
        tmp += this.tgString.charAt((this.cYear - 4) % 10);
        tmp += this.dzString.charAt((this.cYear - 4) % 12);
        tmp += "(";
        tmp += this.sx.charAt((this.cYear - 4) % 12);
        tmp += ")年 ";
        if (this.cMonth < 1) {
            tmp += "(闰)";
            tmp += this.monString.charAt(-this.cMonth - 1);
        } else {
            tmp += this.monString.charAt(this.cMonth - 1);
        }
        tmp += "月";
        tmp += (this.cDay < 11) ? "初" : ((this.cDay < 20) ? "十" : ((this.cDay < 30) ? "廿" : "三十"));
        if (this.cDay % 10 != 0 || this.cDay == 10) {
            tmp += this.numString.charAt((this.cDay - 1) % 10);
        }
        return tmp;
    }

    GetLunarDay(solarYear, solarMonth, solarDay) {
        if (solarYear < 1921 || solarYear > 2025) {
            return "";
        } else {
            solarMonth = (parseInt(solarMonth) > 0) ? (solarMonth - 1) : 11;
            this.e2c(solarYear, solarMonth, solarDay);
            return this.GetcDateString();
        }
    }

    showCal() {
        var D = new Date();
        var yy = D.getFullYear();
        var mm = D.getMonth() + 1;
        var dd = D.getDate();
        var ww = D.getDay();
        return this.GetLunarDay(yy, mm, dd);
    }

    async test() {
        if (config.runsInWidget) {
            return
        }
        this.widgetSize = 'small'
        let s = await this.render()
        await s.presentSmall()
        this.widgetSize = 'medium'
        let m = await this.render()
        await m.presentMedium()
        this.widgetSize = 'large'
        let l = await this.render()
        await l.presentLarge()
    }

    async renderLarge() {
        return await this.renderSmall(2)
    }

    async init() {
        if (config.runsInApp) {
            return
        }
        let widget = await this.render()
        Script.setWidget(widget)
        Script.complete()
    }
}

module.exports = Friday
